﻿using System;
using System.Linq;
using BusinessBingo.Data.Filter;
using BusinessBingo.Data.Interfaces;
using BusinessBingo.Model;
using BusinessBingo.Model.Interfaces;
using BusinessBingo.Queries;
using BusinessBingo.QueryHandlers.Base;
using BusinessBingo.QueryHandlers.Interfaces;
using BusinessBingo.QueryHandlers.Results;

namespace BusinessBingo.QueryHandlers
{
    public class GetUserQueryHandler : BaseQueryHandler, IGetUserQueryHandler
    {
        private IUserRepository _userRepository;

        public GetUserQueryHandler(
            IUserRepository userRepository,
            IValidationState validationState)
            : base(validationState)
        {
            this._userRepository = userRepository;
        }

        public GetUserQueryHandlerResult Execute(GetUserQuery getUserQuery)
        {
            GetUserQueryHandlerResult result = new GetUserQueryHandlerResult();

            if(getUserQuery == default(GetUserQuery))
                throw new ArgumentNullException("GetUserQuery");
            if (getUserQuery.UserId == default(Guid))
            {
                this._validationState.AddError<GetUserQuery>(x => x.UserId, ErrorTypes.Empty);
            }

            if(this._validationState.IsValid == false)
                return result;

            UserFilter filter = new UserFilter();
            filter.WithId = getUserQuery.UserId;
            
            User user = this._userRepository.GetItems(null, null, filter).Single();
            
            result.Succeeded = true;
            result.User = user;

            return result;
        }
    }
}